package com.heima.admin.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminUserMapper;
import com.heima.admin.service.AdminUserService;
import com.heima.model.admin.datos.AdminUserDto;
import com.heima.model.admin.pojos.AdminUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 朱安东
 * @version 1.0
 * @project leadnews-project
 * @date 2024/1/24 22:37:17
 */
@Service
@Slf4j
@Transactional
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements AdminUserService {
    /**
     * 登录
     *
     * @param adminUserDto 管理员用户 DTO
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult login(AdminUserDto adminUserDto) {
        //1.判断用户的用户名和密码是否正确
        if(StringUtils.isEmpty(adminUserDto.getName()) || StringUtils.isEmpty(adminUserDto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不存在");
        }

        //2.查询是否存在用户名
        AdminUser adminUser = getOne(Wrappers.<AdminUser>lambdaQuery().eq(AdminUser::getName, adminUserDto.getName()));
        if(adminUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3.对前端穿进来的密码做加盐处理与数据库中做比对
        String salt = adminUser.getSalt();
        String password = adminUserDto.getPassword();
        password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if(password.equals(adminUser.getPassword())){
            //4.返回数据  jwt
            Map<String,Object> map  = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(adminUser.getId()));
            adminUser.setSalt("");
            adminUser.setPassword("");
            map.put("user",adminUser);
            return ResponseResult.okResult(map);

        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ACCOUNT_PASSWORD_ERROR);
        }
    }
}
